package com.atguigu.tingshu.album.consumer;

import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/***
 * 监听redis一致性消息：专辑修改/删除
 */
@Log4j2
@Component
@AllArgsConstructor
public class RedisMessageConsumer {

    private RedisTemplate redisTemplate;

    /**
     * 发生专辑修改/删除时 删除redis中的专辑数据
     *
     * @param message 消息
     * @param channel 通道
     */
    @SneakyThrows
    @RabbitListener(queues = "album_and_search_queue_redis")
    public void redisMessageConsumerListener(Message message, Channel channel) {
        // 从消息中获取专辑id
        Long albumId = Long.valueOf(new String(message.getBody()));
        // 获取专辑属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取专辑编号
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            // 删除redis中专辑数据
            redisTemplate.delete("getAlbumInfo:" + Arrays.asList(albumId).toString());
            // 删除统计数据
            redisTemplate.delete("getAlbumStatMap:" + Arrays.asList(albumId).toString());
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            // 判断消息是否重复投递
            if (messageProperties.getRedelivered()) {
                // 是：记录日志 丢弃消息
                log.error("删除redis中的专辑数据失败,失败的原因为:" + e.getMessage() + ",专辑的id为:" + albumId);
                channel.basicReject(deliveryTag, false);
            } else {
                // 不是: 重新投递
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
